package com.google.code.virtualhockey.vhx.server.servlet

import javax.servlet.http.{HttpServletResponse, HttpServletRequest, HttpServlet}
import java.util.logging.{Level, Logger}
import com.google.appengine.api.datastore.EntityNotFoundException
import com.google.code.virtualhockey.vhx.sds.{SNameKey, Sds}
import com.google.code.virtualhockey.vhx.server.model.Image
import com.google.code.virtualhockey.vhx.util.LangUtils

/**
 * Serves images from the datastore.
 */
class VhxImageServlet extends HttpServlet {

  override def doPost(rq: HttpServletRequest, rp: HttpServletResponse ) {
    doGet( rq, rp )
  }

  override def doGet( rq: HttpServletRequest, rp: HttpServletResponse ) {
    var id = rq.getParameter( VhxImageServlet.PARAM_ID )

    if ( id == null ) {
      VhxImageServlet.LOG.log( Level.WARNING, "VhxImageServlet called without " + VhxImageServlet.PARAM_ID + " parameter." )
      return
    }

    LangUtils.withResource( rp.getOutputStream ) { out =>
      try {
        val img = Sds().get( new SNameKey[Image]( id ) )

        // cache all images for 28 days (4 weeks)
        //
        rp.setHeader( "Cache-control", "max-age=" + VhxImageServlet.CACHE_MAX_AGE )
        rp.setContentType( img.mimeType )
        rp.setContentLength( img.data.length )

        out.write( img.data )
      }
      catch {
        case ex: EntityNotFoundException => VhxImageServlet.LOG.log( Level.WARNING, "Found no image for id: " + id )
      }
    }
  }
}

object VhxImageServlet {
  protected val LOG: Logger = Logger.getLogger( classOf[VhxImageServlet].getName )
  protected val PARAM_ID: String = "id"
  protected val CACHE_MAX_AGE: Int = 3600 * 24 * 28
}
